var rurl = "/tFile/";
var rwurl = "/tFileWeb/";

var $ = layui.$;
var table = layui.table //表格
var laypage = layui.laypage; //分页
var form = layui.form;
var flow = layui.flow;
var element = layui.element;
var upload = layui.upload;

var toEdit;
var isadd = true;
var mypage = 1;
var mylimit = 10;
var actiontable="";



//加载模块（从layui 2.6 开始，第一个参数不传即代表加载所有内置模块）
layui.use(['form', 'table'], function () { //加载特定模块：layui.use(['layer', 'laydate', function(){
    //得到各种内置组件

    var layer = layui.layer //弹层
        , element = layui.element //元素操作

    //表单监听
    form.on('switch(switchTest)', function (data) {
        layer.msg('开关checked：' + (this.checked ? 'true' : 'false'), {
            offset: '6px'
        });
        layer.tips('温馨提示：请注意开关状态的文字可以随意定义，而不仅仅是ON|OFF', data.othis)
    });

    form.on('submit(submitBtn)', function (data) {
        var condiction = JSON.stringify(data.field);
        console.log(condiction);
        var mysearch=[data.field,{"sortType":"DESC","sortStr":"name"}];
        searchdata(condiction);
        return false;
    });


    //监听行单击事件（双击事件为：rowDouble，单击事件：row）
    table.on('rowDouble(tmlist)', function (obj) {
        var data = obj.data;
        //标注选中样式
        obj.tr.addClass('layui-table-click').siblings().removeClass('layui-table-click');
        toEdit = data;
        isadd = false;
        openEdit();
    });

    //分页初始化
    laypage.render({
        elem: 'mylaypage' //分页容器的id
        , count: 100 //总页数
        , skin: '#1E9FFF' //自定义选中色值
        , layout: ['count', 'prev', 'page', 'next', 'limit', 'refresh', 'skip']
        //,skip: true //开启跳页
        , jump: function (obj, first) {
            if (!first) {
                //加载分页数据，用重载方法
                //getRemoteData(obj.curr, obj.limit);
                mypage = obj.curr;
                mylimit = obj.limit;
                console.log(mypage + "mypage " + mylimit);
                reFresh();
                layer.msg('第' + obj.curr + '页', {offset: 'b'});
            }
        }
    });

    //监听Tab切换
    element.on('tab(tablist)', function (data) {
        layer.tips('切换了 ' + data.index + '：' + this.innerHTML, this, {
            tips: 1
        });
    });

    //--------------------table---------------------

    //监听单元格编辑,快速修改
    table.on('edit(tmlist)', function (obj) {
        var value = obj.value //得到修改后的值
            , data = obj.data //得到所在行所有键值
            , field = obj.field; //得到字段
        layer.msg('[ID: ' + data.id + '] ' + field + ' 字段更改为：' + value);
        quickUpdateData(data.id, field, value);
    });

    //监听头工具栏事件
    table.on('toolbar(tmlist)', function (obj) {
        var checkStatus = table.checkStatus(obj.config.id)
            , data = checkStatus.data; //获取选中的数据
        switch (obj.event) {
            case 'add':
                layer.msg('添加');
                isadd = true;
                openEdit();
                break;
            case 'update':
                if (data.length === 0) {
                    layer.msg('请选择一行');
                } else if (data.length > 1) {
                    toAddAction(checkStatus.data,"updatamain");
                    layer.msg('添加到操作区');
                } else {
                    toEdit = checkStatus.data[0];
                    isadd = false;
                    openEdit();
                }
                break;
            case 'delete':
                if (data.length === 0) {
                    layer.msg('请选择一行');
                } else {
                    console.log(checkStatus.data);
                    layer.confirm('真的删除行么', function (index) {
                        for (var deletedata of checkStatus.data) {
                            console.log(deletedata);
                            delData(deletedata.id);
                        }
                        layer.close(index);
                        reFresh();
                    });
                }
                break;
        }
    });

    //--------------------table---------------------
    //初始化数据
    reFresh();
});

//监听工具条
table.on('tool(tmlist)', function (obj) {
    var data = obj.data;
    if (obj.event === 'detail') {
        layer.msg('ID：' + data.id + ' 的查看操作');
    } else if (obj.event === 'del') {
        layer.confirm('真的删除行么', function (index) {
            obj.del();
            layer.close(index);
        });
    } else if (obj.event === 'edit') {
        layer.alert('编辑行：<br>' + JSON.stringify(data))
    }
});



function addData(data) {
    sendRequst("POST", data, rurl);
}

function delData(id) {
    sendRequst("DELETE", "", rurl + id);
}

function updData(data,id) {
    sendRequst("PUT", data, rurl + id);
}

function getData(id) {
    return sendRequst("GET", "", rurl + id);
}
function shuxin(){
    $("#submitBtn").click();
}

function reFresh(){
    setTimeout("shuxin()", 150 )
    return false;
}



function quickUpdateData(id, field, value) {
    var data = "{\"id\":" + id + ",\"" + field + "\"" + ":\"" + value + "\"}";
    sendRequst("PUT", data, rurl + id);
}


function searchdata(condition, page, limit) {
 //   var da = "{\"page\":1,\"limit\":10,\"name\":\"" + condition + "\"}";da = "{\"name\":\"" + condition + "\"}";
     page = mypage;
     limit = mylimit;
    var redata = sendRequst("POST", condition, rurl + "search/" + page + "/" + limit);
    console.log(redata);
}

var levelx=0;
function openEdit(level) {
    levelx=level;
    layer.open({
        type: 2
        , title: '详细页'
        , content: rwurl + "detail"//页面路径
        , maxmin: true
        , area: ['750px', '750px']
        , btn: ['确定', '取消']
        , yes: function (index, layero) {
            //点击确认触发 iframe 内容中的按钮提交
            var submit = layero.find('iframe').contents().find("#layuiadmin-app-form-submit");
            submit.click();

            reFresh();
            if(levelx==2){
                showDetail(condition);
            }
        }
    });
}


function sendRequst(typex, datax, urlx) {
    $.ajax({
        url: urlx,
        type: typex,
        data: datax,
        contentType: "application/json;charset=utf-8",
        success: function (data) {
            console.log(data);
            if (urlx.search("search") != -1) {
                table.reload('tmlist', {
                    data: data.data.list,
                    limit:mylimit
                });
                laypage.render({
                    elem: 'mylaypage' //分页容器的id
                    , count:data.data.total //总页数
                   , skin: '#1E9FFF' //自定义选中色值
                    , layout: ['count', 'prev', 'page', 'next', 'limit', 'refresh', 'skip']
                    ,curr:data.data.pageNum
                    ,limit:data.data.pageSize
                    //,skip: true //开启跳页
                    , jump: function (obj, first) {
                        if (!first) {
                            mypage=obj.curr;
                            mylimit=obj.limit;
                            console.log(mypage+"mypage "+mylimit);
                            reFresh();
                            layer.msg('第' + obj.curr + '页', {offset: 'b'});
                        }
                    }
                });


            }
        },
        error: function (data) {
            console.log('error');
            return data;
        }
    });
}